/* 公共函数 */

// 计算两个日期相差多少年多少月多少天
export function dateDifference(date1: Date, date2: Date): [number, number, number] {
    if (date1 < date2) {
        [date1, date2] = [date2, date1];
    }
    let years = date1.getFullYear() - date2.getFullYear();
    let months = date1.getMonth() - date2.getMonth();
    let days = date1.getDate() - date2.getDate();
    if (days < 0) {
        let lastDayOfMonth = new Date(date2.getFullYear(), date2.getMonth() + 1, 0);
        months--;
        days += lastDayOfMonth.getDate();
    }	
	if (months < 0) {
	    years--;
	    months += 12;
	}
    return [years, months, days];
}

/* 格式化显示 */

// 根据出生日期，显示年龄
export function birthday2age(birthday: Date): string {
	const diff = dateDifference(birthday, new Date());
	const years = diff[0];
	const months = diff[1];
	const days = diff[2];
	var result = '';
	if (years == 0) {
		if (months == 0) {
			result = days + '天';
		} else {
			result = months + '个月 ' + days + '天';
		}
	} else if (years < 3) {
		if (months == 0) {
			result = years + '岁';
		} else {
			result = years + '岁 ' + months + '个月';
		}
	} else {
		result = years + '岁';
	}
	return result;
}

// 根据整数值，显示性别
export function integer2sex(sex: number): string {
	return sex == 0 ? '女' : sex == 1 ? '男' : '';
}

// 根据性别，获得整数值
export function sex2integer(sex: string): number {
	return sex == '女' ? 0 : sex == '男' ? 1 : 2;
}

// 将日期格式化为'20250107'这种格式的字符串
export function encodeDate(d : Date): string {
	return `${String(d.getFullYear()).padStart(4, '0')}${String(d.getMonth() + 1).padStart(2, '0')}${String(d.getDate()).padStart(2, '0')}`;
}

// 将日期格式化为'2025-01-07'这种格式的字符串
export function formatDate(d : Date): string {
    return `${String(d.getFullYear()).padStart(4, '0')}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}

// 将日期格式化为'2025-01-07 20:01'这种格式的字符串
export function formatDatetime(d : Date):string {
    const year = String(d.getFullYear());
    const month = String(d.getMonth() + 1).padStart(2, '0'); // 月份从0开始，加1，并且补零
    const day = String(d.getDate()).padStart(2, '0'); // 补零
    const hours = String(d.getHours()).padStart(2, '0'); // 补零
    const minutes = String(d.getMinutes()).padStart(2, '0'); // 补零
 
    return `${year}-${month}-${day} ${hours}:${minutes}`;
}